package GameObjects;

import java.awt.geom.Ellipse2D;
import java.util.List;

import main.Main;

public class Circle extends Ellipse2D.Double implements GameObject{

	private static final long serialVersionUID = 2884133570644425172L;
	
	final double radius;
	double theta;
	int speed;
	
	public Circle(double x,double y,double w,double h, int speed, double theta){		
		super(x, y, w, h);
		this.radius = h;
		this.theta =  theta % (Math.PI * 2.0d);
		this.speed = speed;
	}
	
	public void move(double theta, int speed){
		double x = getCenterX();
		double y = getCenterY();
		x +=  speed * Math.cos(theta);
		y -= speed * Math.sin(theta);	
		setFrameFromCenter(x, y, x + radius, y+radius);
	}
	
	public void move(){
		move(theta, speed);
	}
	
	
	@Override
	public void updateState() {
		
		if(getCenterY() < 0){//make "Walls" a GameObject to collide With?
			if(theta < Math.PI/2.0d){
				theta =  2.0d*Math.PI - theta;
			}else{
				theta = Math.PI+ (Math.PI - theta);
			}
			//move();
		}else if(getCenterY() > Main.WINDOW_HEIGHT){
			if(theta > 3.0d*Math.PI/2.0d){				
				theta =  2.0d*Math.PI - theta;
			}else{
				theta =  Math.PI/2.0d +  (3.0d*Math.PI/2.0d - theta);
			}
			//move();
		}
		
	}
	
	
	public void handleCollisions(List<GameObject> objs){
		double centerX =  getCenterX();
		double centerY = getCenterY();
		double radius = getHeight() / 2;
				
		for(GameObject other : objs){
					
			if(isMovingRight()){
				
				//minX < centerX < maxX
				if(centerX > Math.abs(other.getBounds2D().getMinX() - radius)
						&& centerX < Math.abs(other.getBounds2D().getMaxX()-radius) ){
	//				System.out.println("CenterX:"+centerX+" radius:"+radius+" MinX:"+other.getBounds2D().getMinX()+ " maxX:"+other.getBounds2D().getMaxX());
					if(centerY > other.getBounds2D().getMinY() && centerY < other.getBounds2D().getMaxY()){
						bounceLeft();
						move();
						move();
						return;//dont collide with > 1 object per frame
					}
				}
			}else{//moving left
				
				// getMinX <  centerX-radius  < getMaxX 
				if(centerX-radius > other.getBounds2D().getMinX()
						&& centerX-radius < other.getBounds2D().getMaxX() ){
					if(centerY > other.getBounds2D().getMinY() && centerY < other.getBounds2D().getMaxY()){
						bounceRight();
						move();
						move();
						return;
					}
				}				
			}
			
		}
	}
	
	
	private void bounceRight(){
		if( theta < Math.PI){
			theta = Math.PI/2 - (theta - Math.PI/2.0d);
		}else {
			theta = (2.0d*Math.PI) - (theta - Math.PI);
		}
	}

	private void bounceLeft(){
		if(theta >= 0){
			theta = Math.PI - theta;
		}else {
			theta = Math.PI - (2.0d*Math.PI - theta);
		}		
	}
	
	private boolean isMovingRight(){
		theta %= 2.0d*Math.PI;
		return (theta < Math.PI / 2  || theta > 1.5d * Math.PI );
	}
	
}
